<template>
  <div class="user-log-view">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <span>用户操作日志</span>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryForm" inline class="query-form">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="queryForm.action" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="LOGIN" />
            <el-option label="登出" value="LOGOUT" />
            <el-option label="访问页面" value="ACCESS_PAGE" />
            <el-option label="创建用户" value="CREATE_USER" />
            <el-option label="更新用户" value="UPDATE_USER" />
            <el-option label="删除用户" value="DELETE_USER" />
            <el-option label="创建角色" value="CREATE_ROLE" />
            <el-option label="更新角色" value="UPDATE_ROLE" />
            <el-option label="删除角色" value="DELETE_ROLE" />
            <el-option label="更新权限" value="UPDATE_ROLE_PERMISSIONS" />
            <el-option label="创建客户" value="CREATE_CUSTOMER" />
            <el-option label="更新客户" value="UPDATE_CUSTOMER" />
            <el-option label="删除客户" value="DELETE_CUSTOMER" />
            <el-option label="审核客户" value="APPROVE_CUSTOMER" />
            <el-option label="创建部门" value="CREATE_DEPARTMENT" />
            <el-option label="更新部门" value="UPDATE_DEPARTMENT" />
            <el-option label="删除部门" value="DELETE_DEPARTMENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 日志表格 -->
      <el-table :data="logs" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="action" label="操作类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getActionType(row.action)">
              {{ getActionName(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" />
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="createdAt" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

interface UserLog {
  id: number
  user: {
    username: string
  }
  action: string
  description: string
  ipAddress: string
  createdAt: string
}

interface QueryForm {
  username: string
  action: string
  timeRange: [string, string] | null
}

const logs = ref<UserLog[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const queryForm = reactive<QueryForm>({
  username: '',
  action: '',
  timeRange: null
})

// 获取操作类型标签样式
const getActionType = (action: string) => {
  const types: Record<string, string> = {
    'LOGIN': 'success',
    'LOGOUT': 'info',
    'ACCESS_PAGE': 'info',
    'CREATE_USER': 'success',
    'UPDATE_USER': 'warning',
    'DELETE_USER': 'danger',
    'CREATE_ROLE': 'success',
    'UPDATE_ROLE': 'warning',
    'DELETE_ROLE': 'danger',
    'UPDATE_ROLE_PERMISSIONS': 'info',
    'CREATE_CUSTOMER': 'success',
    'UPDATE_CUSTOMER': 'warning',
    'DELETE_CUSTOMER': 'danger',
    'APPROVE_CUSTOMER': 'info',
    'CREATE_DEPARTMENT': 'success',
    'UPDATE_DEPARTMENT': 'warning',
    'DELETE_DEPARTMENT': 'danger'
  }
  return types[action] || 'info'
}

// 获取操作类型显示名称
const getActionName = (action: string) => {
  const names: Record<string, string> = {
    'LOGIN': '登录',
    'LOGOUT': '登出',
    'ACCESS_PAGE': '访问页面',
    'CREATE_USER': '创建用户',
    'UPDATE_USER': '更新用户',
    'DELETE_USER': '删除用户',
    'CREATE_ROLE': '创建角色',
    'UPDATE_ROLE': '更新角色',
    'DELETE_ROLE': '删除角色',
    'UPDATE_ROLE_PERMISSIONS': '更新权限',
    'CREATE_CUSTOMER': '创建客户',
    'UPDATE_CUSTOMER': '更新客户',
    'DELETE_CUSTOMER': '删除客户',
    'APPROVE_CUSTOMER': '审核客户',
    'CREATE_DEPARTMENT': '创建部门',
    'UPDATE_DEPARTMENT': '更新部门',
    'DELETE_DEPARTMENT': '删除部门'
  }
  return names[action] || action
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取日志列表
const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      username: queryForm.username || undefined,
      action: queryForm.action || undefined,
      startDate: queryForm.timeRange?.[0] || undefined,
      endDate: queryForm.timeRange?.[1] || undefined
    }

    const response = await axios.get('/api/logs', { params })
    logs.value = response.data.content
    total.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  currentPage.value = 1
  fetchLogs()
}

// 重置查询
const resetQuery = () => {
  queryForm.username = ''
  queryForm.action = ''
  queryForm.timeRange = null
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchLogs()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchLogs()
}

// 初始化
fetchLogs()
</script>

<style scoped>
.user-log-view {
  padding: 20px;
}

.log-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 80px;
}
</style>
